package com.platform.cdcs.fragment.stock;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.MyApp;
import com.platform.cdcs.R;
import com.platform.cdcs.fragment.detail.ProductInfoFragment;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.HouseItem;
import com.platform.cdcs.model.ProductList;
import com.platform.cdcs.model.StockTakeProduct;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.FragmentUtil;
import com.platform.cdcs.tool.ViewTool;
import com.platform.cdcs.widget.ChooseWindow;
import com.sherchen.slidetoggleheader.views.ObservableXListView;
import com.sherchen.slidetoggleheader.views.XListView;
import com.trueway.app.uilib.adapter.EnhancedAdapter;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.model.ChooseItem;
import com.trueway.app.uilib.tool.Utils;
import com.trueway.app.uilib.widget.TwDialogBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by holytang on 2017/10/30.
 */
public class InStockDetailFrgment extends BaseFragment {


    private ItemAdapter adapter;
    private TextView titleView;
    private List<ChooseItem> stockList;
    private int pageIndex = 1;
    private ObservableXListView listView;
    private String stockId;
    private String inType;
    private String whName = "";
    private String itemCode = "";
    private String desc = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            stockId = getArguments().getString("stockId");
            inType = getArguments().getString("inType");
            itemCode = getArguments().getString("itemCode");
            desc = getArguments().getString("desc");
        }
    }

    @Override
    public void initView(View view) {
        adapter = new ItemAdapter(getContext());
        initLoadImg(view.findViewById(R.id.load));
        hideThisToolBar(view);
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        setTitle(itemCode);
        listView = (ObservableXListView) view.findViewById(android.R.id.list);
        View headerView = LayoutInflater.from(getContext()).inflate(R.layout.left_right, null);
        titleView = (TextView) headerView.findViewById(R.id.title);
        titleView.setText(ViewTool.makeArrorDown("所有库位", "▼"));
        titleView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showStock();
            }
        });

        TextView rightView = (TextView) headerView.findViewById(R.id.text);
        rightView.setText(desc);
        listView.addHeaderView(headerView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //详情页面
                ProductList.ProductItem item = (ProductList.ProductItem) adapterView.getItemAtPosition(i);
                Bundle bundle = new Bundle();
                bundle.putSerializable("model", item);
                FragmentUtil.navigateToInNewActivity(getActivity(), ProductInfoFragment.class, bundle);
            }
        });
        listView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                adapter.clear();
                adapter.notifyDataSetChanged();
                requestList(false);
            }

            @Override
            public void onLoadMore() {
                requestList(false);
            }
        });
        listView.setAdapter(adapter);
        requestList(true);
    }

    @Override
    public int layoutId() {
        return R.layout.listview;
    }

    private void requestList(boolean flag) {
        if (flag) {
            showLoadImg();
        }
        showLoadImg();
        Map<String, String> param = new HashMap<>();
        param.put("stockId", stockId);
        param.put("pageSize", String.valueOf(Constant.PAGE_SIZE));
        param.put("pageIndex", String.valueOf(pageIndex));
        param.put("itemCodes", itemCode);
        param.put("subBUs", "");
        param.put("inType", inType);
        param.put("whName", whName);
        param.put("distCode", MyApp.getInstance().getAccount().getOrgId());
        getHttpClient().post().url(Constant.DistSysStockTakeProductDetailLst).params(Constant.makeParam(param)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                listView.stopRefresh();
                listView.stopLoadMore();
                dismissLoadImg();
                Utils.showToast(getActivity(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    dismissLoadImg();
                    listView.stopRefresh();
                    listView.stopLoadMore();
                    Type type = new TypeToken<BaseObjResponse<StockTakeProduct>>() {
                    }.getType();
                    BaseObjResponse<StockTakeProduct> response = new Gson().fromJson(s, type);
                    if ("1".equals(response.getResult().getCode())) {
                        adapter.addAll(response.getResult().getDistSysStockTakeProductList());
                        adapter.notifyDataSetChanged();
                        if (response.getResult().getDistSysStockTakeProductList().size() == Constant.PAGE_SIZE) {
                            pageIndex++;
                            listView.setPullLoadEnable(true);
                        } else {
                            listView.setPullLoadEnable(false);
                        }
                    } else {
                        Utils.showToast(getContext(), response.getResult().getMsg());
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    private void showStock() {
        if (stockList == null) {
            showLoadImg();
            getHttpClient().post().url(Constant.DIST_WHHOUSE_LST).params(Constant.makeParam(new HashMap<String, String>())).build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int i) {
                    dismissLoadImg();
                    Utils.showToast(getActivity(), R.string.server_error);
                }

                @Override
                public void onResponse(String s, int i) {
                    dismissLoadImg();
                    Type type = new TypeToken<BaseObjResponse<HouseItem.HouseList>>() {
                    }.getType();
                    BaseObjResponse<HouseItem.HouseList> response = new Gson().fromJson(s, type);
                    if ("1".equals(response.getResult().getCode())) {
                        final List<HouseItem> items = new ArrayList<HouseItem>();
                        for (HouseItem item : response.getResult().getHouseList()) {
                            if ("1".equals(item.getIsMainHouse())) {
                                items.add(0, item);
                            } else {
                                items.add(item);
                            }
                        }
                        HouseItem allItem = new HouseItem();
                        allItem.setWhCode("");
                        allItem.setWhName("全部");

                        items.add(0, allItem);
                        stockList = new ArrayList<ChooseItem>();
                        for (HouseItem item : items) {
                            ChooseItem cItem = new ChooseItem();
//                            cItem.setTitle(item.getWhName());
                            cItem.setText(item.getWhCode());
                            cItem.setTime(item.getWhName());
                            stockList.add(cItem);
                        }
                        if (stockList.size() > 0) {
                            showStock();
                        } else {
                            stockList = null;
                            Utils.showToast(getContext(), "暂无库位");
                        }
                    } else {
                        Utils.showToast(getContext(), response.getResult().getMsg());
                    }

                }
            });
        } else {
            final ChooseWindow window = new ChooseWindow(getContext());
//            window.setType(1);
            window.setData(stockList, "库位", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    window.dismiss();
                    String stock = window.getChooseName();
                    if (stock.contains("全部")) {
                        stock = "";
                    }
                    pageIndex = 1;
                    adapter.clear();
                    adapter.notifyDataSetChanged();
                    whName = stock;
                    if (TextUtils.isEmpty(stock)) {
                        titleView.setText(ViewTool.makeArrorDown("所有库位", "▼"));
                    } else {
                        titleView.setText(ViewTool.makeArrorDown(whName, "▼"));
                    }
                    requestList(true);
                }
            });
            window.show((View) titleView.getParent());
        }
    }

    private class ItemAdapter extends EnhancedAdapter<ProductList.ProductItem> {

        public ItemAdapter(Context context) {
            super(context);
        }

        @Override
        protected void bindView(View paramView, Context paramContext, int position) {
            ViewHolder holder = (ViewHolder) paramView.getTag();
            ProductList.ProductItem item = getItem(position);
            if (!TextUtils.isEmpty(item.getSerialNumber())) {
                holder.titleView.setText(item.getSerialNumber());
            } else if (!TextUtils.isEmpty(item.getBatchNumber())) {
                holder.titleView.setText("批号 " + item.getBatchNumber());
            }else{
                holder.titleView.setText("序列号、批号未知产品");
            }
            holder.textView.setText("失效期 " + item.getExpDate());
//            if (!TextUtils.isEmpty(item.getExpDate())) {
//                holder.textView.setText("失效期 " + item.getExpDate());
//            } else {
//                holder.textView.setText("");
//            }
//            holder.descView.setText(item.getWhName());
            holder.dateView.setText(String.format("%s %s", item.getQty(), item.getUom()));
            holder.descView.setText(item.getWhName());

        }

        @Override
        protected View newView(Context context, int position, ViewGroup viewgroup) {
            View rootView = null;
            rootView = inflater.inflate(R.layout.four_item, viewgroup, false);
            rootView.setBackgroundResource(R.drawable.shape_corner_center);
            ViewHolder holder = new ViewHolder();
            holder.titleView = (TextView) rootView.findViewById(R.id.title);
            holder.dateView = (TextView) rootView.findViewById(R.id.time);
            holder.textView = (TextView) rootView.findViewById(R.id.text);
            holder.descView = (TextView) rootView.findViewById(R.id.desc);
            holder.textView.setSingleLine(false);
            holder.textView.setMaxLines(2);
            rootView.setTag(holder);
            return rootView;
        }

    }

    private class ViewHolder {
        TextView titleView, dateView, textView, descView;
    }
}
